import logging
import keyboard
import file_processor
import table_processor
import config
import re
import os
from aiogram.contrib.fsm_storage.files import JSONStorage
from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types.message import ContentType


TOKEN = os.environ['TG_TOKEN']

storage = JSONStorage(config.get_state_path())
bot = Bot(token=TOKEN)
dp = Dispatcher(bot, storage=storage)
file_processor.load_cache()
table_processor.parse_tables()

class BotState(StatesGroup):

    common = State()
    save = State()
    choose = State()
    read = State()



@dp.message_handler(state='*', text='start', content_types=[ContentType.TEXT])
async def set_commmon_state(message: types.Message()):
    await BotState().common.set()
    await message.answer(text='Выберите команду', reply_markup=keyboard.COMMON_KEYBOARD)

@dp.message_handler(state='*', content_types=[ContentType.TEXT], text='Открыть таблицу')
async def get_data(message: types.Message()):
    await BotState().choose.set()
    if len(table_processor.NAMES_LIST) != 0:
        await message.answer(text='Выберите таблицу', reply_markup=keyboard.gen_reply_keyboard(table_processor.NAMES_LIST))
    else:
        await BotState().common.set()
        await message.answer(text='Файл не загружен', reply_markup=keyboard.COMMON_KEYBOARD)

@dp.callback_query_handler(state=BotState().choose)
async def open_table(callback_query: types.CallbackQuery):
    response = table_processor.get_data(callback_query.from_user.username, str(callback_query.data), 'next')
    if response is None:
        await BotState().common.set()
        await bot.send_message(
            callback_query.from_user.id,
            text='Ошибка данных',
            reply_markup=keyboard.COMMON_KEYBOARD)
    else:
        await BotState().read.set()
        await bot.send_message(
            chat_id=callback_query.from_user.id,
            text=response,
            reply_markup=keyboard.INLINE_CONTROL_PANEL
        )


@dp.callback_query_handler(state=BotState().read, regexp=r'(next|back)')
async def get_table_next_line(callback_query: types.CallbackQuery):
    response = table_processor.get_dir_data(callback_query.from_user.username, str(callback_query.data))
    if response is None:
        await callback_query.answer("Данных нет", show_alert=False)
    else:
        await callback_query.message.edit_text(text = response, reply_markup=keyboard.INLINE_CONTROL_PANEL)



@dp.message_handler(state=BotState().save, content_types=[ContentType.DOCUMENT, ContentType.TEXT])
async def save_file(message: types.Message):
    if message.document and re.search(r'.*\.xlsx', message.document.file_name):
        await file_processor.save_file(message.document)
        await message.answer(text='Документ сохранен', reply_markup=keyboard.COMMON_KEYBOARD)
    else:
        await message.answer(text='Документ не получен', reply_markup=keyboard.COMMON_KEYBOARD)
    await BotState().common.set()

@dp.message_handler(state=BotState().common, content_types=[ContentType.TEXT], text='Загрузить файл')
async def upload_file(message: types.Message):
    await BotState().save.set()
    await bot.send_message(
        chat_id=message.from_user.id,
        text='Ожидаю документ'
    )

# @dp.callback_query_handler(state=BotState().common, text='get_info')
# async def get_info(callback_query: types.CallbackQuery):
#     await bot.send_message(
#         chat_id=callback_query.from_user.id,
#         text='Надо поспать',
#         reply_markup=keyboard.COMMON_KEYBOARD
#     )

# @dp.callback_query_handler(state='*', text='save')
# async def call_save_file(callback_query: types.CallbackQuery):
#     await BotState().save.set()
#     await bot.answer_callback_query(callback_query.id)
#     await bot.send_message(
#         chat_id=callback_query.from_user.id,
#         text='Ожидаю документ',
#         reply_markup=types.ReplyKeyboardRemove()
#     )

@dp.message_handler(state='*', text='Получить файл')
async def get_file(callback_query: types.CallbackQuery):
    file_id = file_processor.get_file_id()
    file_name = file_processor.get_file_name()
    if file_id:
        await bot.send_document(callback_query.from_user.id, file_id)
    elif file_name:
        try:
            file = await file_processor.get_file()
            await bot.send_document(chat_id=callback_query.from_user.id, document=(file_name, file))
        except FileNotFoundError:
            await bot.send_message(callback_query.from_user.id, "Файл не найден на диске")
    else:
        await bot.send_message(callback_query.from_user.id, "Файл не был загружен")

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

